#!/bin/bash
# -*- coding:utf-8 -*-

import json 
import urllib
import socket

try: import httplib 
except ImportError: 
    import http.client as httplib

N_REST = '/api/'

P_CODE   = 'status_code'
P_DETAIL = 'detail'
P_RESULT = 'results'

# 查询运维查找脚本位置
HOST_NAME = socket.gethostname() 


def mixStr(pstr):
    if(isinstance(pstr, str)):
        return pstr
    elif(isinstance(pstr, unicode)):
        return pstr.encode('utf-8')
    else:
        return str(pstr)

class ApiBase(object): 
    """ 
    +----------------------------------------------+ 
    +     CMDB api 基类                            +
    +----------------------------------------------+
    """

    def __init__(self, domain='api-ops.fenxibao.com', port = 80): 
        self.__domain = domain 
        self.__port   = port 
        self.__httpmethod = 'GET'
        self.__token  = None
        self.__hostname = HOST_NAME

    def get_request_header(self): 
        """ Requests header""" 
        
        return {
            "content-type" : "application/json" , 
            "charset" : "utf-8" ,
            "Authorization": "Token %s" % self.__token
        }

    def set_token(self, token):
        self.__token = token
    
    def get_api_name(self): 
        return None

    def __str__(self): 
        return '[ api_class : %s ]' % self.get_api_name()

    def getApplicationParameters(self): 
        application_parameter = {}

        for key,value in self.__dict__.iteritems(): 
            if not key.startswith("__") and not key.startswith("ApiBase_") and value is not None :
                if(key.startswith("_")): 
                    application_parameter[key[1:]] = value
                else: 
                    application_parameter[key] = value 
                
        return application_parameter

    def getResponse(self, timeout=30): 
        connection = httplib.HTTPConnection(self.__domain, self.__port, timeout)
        connection.connect() #建立连接

        header = self.get_request_header()  #获取headers 
        application_parameter = self.getApplicationParameters() #获取参数 
        body = urllib.urlencode(application_parameter)  #生成参数连接
        url = N_REST + str(self.get_api_name()) + "/?" + body #合并成完整URL 域名 + 接口 + 参数

        connection.request(self.__httpmethod, url, body=body, headers=header)
        response = connection.getresponse();

        try:
            jsonobj = json.loads(response.read())
        except ValueError as e:
            error = RequestException()   #通常这里会发生404, 500造成的解析异常.
            error.errorcode = response.status
            error.message = str(e)
            raise error

        if jsonobj.has_key('status_code'): 
            error = CmdbException()

            if jsonobj.has_key(P_CODE):
                error.errorcode = jsonobj[P_CODE]
            if jsonobj.has_key(P_DETAIL):
                error.message = jsonobj[P_DETAIL]
            if jsonobj.has_key(P_RESULT):
                error.results = jsonobj[P_RESULT]
            error.application_host = response.getheader("Application-Host", "")
            error.service_host = response.getheader("Location-Host", "")
            raise error
        return jsonobj

class BaseException(Exception):
    """
    接口返回异常基类
    """
    def __init__(self):
        self.errorcode = None
        self.message = None
        self.results = None
        self.application_host = None
        self.service_host = None

    def __str__(self, *args, **kwargs):
        sb = "errorcode=" + mixStr(self.errorcode) +\
                " message=" + mixStr(self.message) +\
                " results=" + mixStr(self.results) +\
                " application_host=" + mixStr(self.application_host) +\
                " service_host=" + mixStr(self.service_host)
        return sb


class CmdbException(BaseException): 
    """CMDB 接口内部异常类型"""
    pass


class RequestException(BaseException): 
    """CMDB 连接异常类"""
    pass
